import React, { useEffect, useState } from 'react'
import style from "./upload.module.css";
import { Popover, Input, Tabs, Button, Upload, message } from 'antd';
import { SearchOutlined, SettingOutlined, DeleteOutlined } from '@ant-design/icons';
import ImgCrop from 'antd-img-crop';



function Index() {
  const [isImgSelected, setIsImgSelected] = useState(true)
  //tab切换事件
  const onChange = (key: string) => {
    console.log(key);
    if (key == '0') {
      setIsImgSelected(true)
    }
    else{
      setIsImgSelected(false)
    }
    setkey(key)
  };
  const items: any = [
    {
      key: '0',
      label: '图片',
      contant: 'Content of Tab Pane 1',
    },
    {
      key: '1',
      label: '视频',
      contant: 'Content of Tab Pane 2',
    },
    {
      key: '2',
      label: '音频',
      contant: 'Content of Tab Pane 3',
    },
  ];
  //上传内容限制
  const content = (
    <div style={{ background: '#1b2337', color: '#fff' }}>
      <p>上传格式支持：</p>
      <p>图片：20MB png、jpeg、svg格式</p>
      <p>动图：5MB以内,gif格式</p>
      <p>视频：100MB、3分钟以内,mp4格式</p>
      <p>音频：20MB、5分钟以内,mp3格式</p>
    </div>
  );
  //tab切换的key值
  const [key, setkey] = useState('0')
  //imglist
  const [fileList, setFileList] = useState(() => {
    const storedFileList = localStorage.getItem('fileList');
    return storedFileList ? JSON.parse(storedFileList) : [];
  });
  useEffect(() => {
    localStorage.setItem('fileList', JSON.stringify(fileList));
  }, [fileList]);

  //上传图片事件
  // const handleChange = async(info: any) => {
  //   console.log(info, '上传的数据');
  //   // const { status, response, name } = info.file;
  //   // if (status === 'done') {
  //   //   // 处理成功的响应
  //   //   if (response && response.result) {
  //   //     console.log(response.result); // 输出上传结果
  //   //     message.success(`${name} 文件上传成功`);
  //   //   } else {
  //   //     console.warn('上传响应中没有 result:', response);
  //   //     message.error(`${name} 文件上传失败，未获取结果`);
  //   //   }
  //   // } else if (status === 'error') {
  //   //   message.error(`${name} 文件上传失败`);
  //   // }
  //   const updatedFileList = info.fileList.map((item: any) => {
  // if (item.type === 'video/mp4') {
  //   const isValidSize = item.size <= 100 * 1024 * 1024; // 100MB
  //   const estimatedDuration = getEstimatedDuration(item.size)
  //   if (!isValidSize || Number(estimatedDuration) > 180) { // 3分钟
  //     message.error(`${item.name} 文件不符合要求：最大100MB和3分钟`);
  //     return Upload.LIST_IGNORE;
  //   }
  // }
  // else if (item.type === 'audio/mpeg') {
  //   const isValidSize = item.size <= 20 * 1024 * 1024; // 20MB
  //   const estimatedDuration = getEstimatedDuration(item.size);

  //   if (!isValidSize || Number(estimatedDuration) > 300) { // 5分钟
  //     message.error(`${item.name} 文件不符合要求：最大20MB和5分钟`);
  //     return Upload.LIST_IGNORE;
  //   }
  // }
  //     return {
  //       ...item,
  //       // url:response.result
  //     }
  //   });

  //   setFileList(updatedFileList); // 更新状态
  //   console.log(fileList, '更新后的数组');
  //   // 将更新后的 fileList 存储到 localStorage
  //   localStorage.setItem('fileList', JSON.stringify(updatedFileList));

  // }
  //判断是否时图片


  const handleChange = async (info: any) => {

    // 这里的 await 会等待 Promise.all() 返回的 Promise 完成，即等待所有异步操作（在这个例子中是对每个文件的处理）执行完毕。
    const updatedFileList = await Promise.all(info.fileList.map(async (item: any) => {
      // 校验文件大小和类型
      const isValidFile = (item: any) => {
        //上传音频
        if (item.type === 'video/mp4') {
          const isValidSize = item.size <= 100 * 1024 * 1024; // 100MB
          const estimatedDuration = getEstimatedDuration(item.size);  //利用下边方法计算时间
          if (!isValidSize || Number(estimatedDuration) > 180) { // 3分钟
            message.error(`${item.name} 文件不符合要求：最大100MB和3分钟`);
            return false;
          }
        }
        if (item.type === 'audio/mpeg') {
          const isValidSize = item.size <= 20 * 1024 * 1024; // 20MB
          const estimatedDuration = getEstimatedDuration(item.size);  //计算时间
          if (!isValidSize || Number(estimatedDuration) > 300) { // 5分钟
            message.error(`${item.name} 文件不符合要求：最大20MB和5分钟`);
            return false;
          }
        }
        return true; // 仅在文件有效时返回 true
      };

      // 校验文件
      const valid = await isValidFile(item);
      if (!valid) {
        return Upload.LIST_IGNORE; // 文件无效，忽略
      }

      // 如果上传成功，添加 URL
      if (item.status === 'done' && item.response && item.response.result) {
        return { ...item, url: item.response.result };
      }

      return item; // 返回原 item 状态
    }));

    // 过滤掉被忽略的文件并更新状态
    const filteredFileList = updatedFileList.filter(item => item !== Upload.LIST_IGNORE);  //限制的文件不能成功上传
    setFileList(filteredFileList);
    localStorage.setItem('fileList', JSON.stringify(filteredFileList));
    console.log(filteredFileList);
  };

  //上传图片
  const props = {
    beforeUpload: (file) => {
      const isImage = ['image/png', 'image/jpeg', 'image/svg+xml'].includes(file.type);
      const isMedia = ['video/mp4', 'audio/mpeg'].includes(file.type);

      // 根据文件类型设置是否显示 ImgCrop
      // setIsImgSelected(isImage); // 仅在是图片时才显示 ImgCrop

      const isValidType = isImage || isMedia;

      if (!isValidType) {
        message.error(`${file.name} 不是png、jpeg、svg、mp4或mp3的格式`);
        return Upload.LIST_IGNORE; // 直接返回无效
      }

      if (file.size / 1024 / 1024 > 20) { // 20MB
        message.error(`${file.name} 文件大小不能超过 20MB`);
        return Upload.LIST_IGNORE; // 直接返回无效
      }

      return true; // 返回 true 允许上传
    },
    onChange: handleChange,
    fileList,
  };

  //粗略计算时常
  const getEstimatedDuration = (size: number) => {
    //音频文件的大小，以字节为单位（例如，2 MB = 2 * 1024 * 1024 字节）
    //出音频的总时长（秒）   * 60 =  1 分钟 = 60 秒  计算出分钟
    return (size / (128 * 1024)) * 60; // 假设128kbps的音频
  };

  //上传视频
  const rendervideo = () => {
    const vid0pFiles = fileList.filter((item: any) => item.type == 'video/mp4')
    return <div>
      {
        vid0pFiles.map((file: any) => {
          return <div className={style.picture} key={file.uid}>
            <video width={200} height='auto' controls>
              <source src={file.url} type={file.type} />
            </video>
            {
              bool1 ? <input type="checkbox" className={style.inpbox}
                checked={selectedvideo.includes(file.name)}
                onChange={() => dx1(file.name)}
              /> : ''
            }
          </div>
        })
      }
    </div>
  }
  //上传音频
  const renderaudio = () => {
    const audilFiles = fileList.filter((item: any) => item.type == 'audio/mpeg')
    return audilFiles.length > 0 ?
      (
        <div>
          {
            audilFiles.map((file: any, index: any) => {
              return <div style={{ position: "relative" }} key={index}>
                <audio key={file.uid} controls style={{ width: '250px' }}>
                  <source src={file.url} type={file.type} />
                </audio>
                {
                  bool2 ? <input type="checkbox"
                    checked={selectedaudio.includes(file.name)}
                    onChange={() => dxaudio(file.name)}
                    style={{ position: 'absolute', right: '5px', top: '20px' }} />
                    : ""
                }
              </div>
            })
          }
        </div>
      )
      : ''
  }




  //设置多选
  const [selectedFiles, setSelectedFiles] = useState([])
  const [selectedvideo, setSelectedvideo] = useState([])
  const [selectedaudio, setSelectedaudio] = useState([])
  const [bool, setBool] = useState(false)
  const [bool1, setBool1] = useState(false)
  const [bool2, setBool2] = useState(false)
  //设置按钮
  const alldx = () => {
    setBool(!bool)
  }
  const [isAllSelected, setIsAllSelected] = useState(false);

  useEffect(() => {
    const allFiles = fileList.filter(file =>
      file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/svg'
    );
    setIsAllSelected(allFiles.length > 0 && allFiles.every(file => selectedFiles.includes(file.name)));
  }, [selectedFiles, fileList]);
  //全选
  const handleSelectAll = (e: any) => {
    const ischecked = e.target.checked;
    const allFiles = fileList.filter((file: any) =>
      file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/svg'
    );
    const updateallFiles = allFiles.map((file: any) => file.name)
    setSelectedFiles(ischecked ? updateallFiles : [])
  }
  //单选
  // console.log(selectedFiles,'单选的数据');
  const dx = (fileName: any) => {
    console.log(fileName);

    if (selectedFiles.includes(fileName)) {
      //如果存在就移出
      const newfiles = selectedFiles.filter(item => item !== fileName)
      setSelectedFiles(newfiles)
      console.log(selectedFiles, 1111);
    }
    else {
      const newfiles = [...selectedFiles, fileName]
      setSelectedFiles(newfiles)
      console.log(selectedFiles, 222);
    }
  }
  //删除
  const delall = () => {
    message.success('删除成功')
    const updatedFileList = fileList.filter(file => !selectedFiles.includes(file.name));
    setFileList(updatedFileList);
    localStorage.setItem('fileList', JSON.stringify(updatedFileList)); // 重新存储
    setSelectedFiles([]); // 清空选中状态
  }



  //视频
  const alldx1 = () => {
    setBool1(!bool1)
  }
  const [isAllSelected1, setIsAllSelected1] = useState(false);

  useEffect(() => {
    const allFiles = fileList.filter(file =>
      file.type === 'video/mp4'
    );
    setIsAllSelected1(allFiles.length > 0 && allFiles.every(file => selectedvideo.includes(file.name)));
  }, [selectedvideo, fileList]);
  // console.log(selectedvideo);
  // 全选
  const handleSelectAll1 = (e: any) => {
    const isChecked = e.target.checked;
    const allFiles = fileList.filter(file => file.type === 'video/mp4');
    const updateAllFiles = allFiles.map(file => file.name);

    setSelectedvideo(isChecked ? updateAllFiles : []); // 根据全选状态更新
  };

  // 单选
  const dx1 = (fileName: any) => {
    if (selectedvideo.includes(fileName)) {
      const newFiles = selectedvideo.filter(item => item !== fileName); // 移除已选择的文件
      setSelectedvideo(newFiles);
    } else {
      const newFiles = [...selectedvideo, fileName]; // 添加新选择的文件
      setSelectedvideo(newFiles);
    }
  };
  //删除
  const delall1 = () => {
    message.success('删除成功')
    const updatedFileList = fileList.filter(file => !selectedvideo.includes(file.name));
    setFileList(updatedFileList);
    localStorage.setItem('fileList', JSON.stringify(updatedFileList)); // 重新存储
    setSelectedvideo([]); // 清空选中状态
  }




  //音频
  const alldx2 = () => {
    setBool2(!bool2)
  }
  const [isAllSelected2, setIsAllSelected2] = useState(false);
  useEffect(() => {
    const allFiles = fileList.filter(file =>
      file.type === 'audio/mpeg'
    );
    setIsAllSelected2(allFiles.length > 0 && allFiles.every(file => selectedaudio.includes(file.name)));
  }, [selectedaudio, fileList]);
  // console.log(selectedaudio);
  // 全选
  const handleSelectAllaudio = (e: any) => {
    const isChecked = e.target.checked;
    const allFiles = fileList.filter(file => file.type === 'audio/mpeg');
    const updateAllFiles = allFiles.map(file => file.name);

    setSelectedaudio(isChecked ? updateAllFiles : []); // 根据全选状态更新
  };

  // 单选
  const dxaudio = (fileName: any) => {
    if (selectedaudio.includes(fileName)) {
      const newFiles = selectedaudio.filter(item => item !== fileName); // 移除已选择的文件
      setSelectedaudio(newFiles);
    } else {
      const newFiles = [...selectedaudio, fileName]; // 添加新选择的文件
      setSelectedaudio(newFiles);
    }
  };
  // //删除
  const delaudio = () => {
    message.success('删除成功')
    const updatedFileList = fileList.filter(file => !selectedaudio.includes(file.name));
    setFileList(updatedFileList);
    localStorage.setItem('fileList', JSON.stringify(updatedFileList)); // 重新存储
    setSelectedaudio([]); // selectedaudio清空选中状态
  }




  return (
    <div className={style.main}>
      <div className={style.top}>
        <h3>
          我的上传
        </h3>
        <Popover content={content}>
          {isImgSelected ? (
            <ImgCrop rotationSlider>
              <Upload
                {...props}
                action="http://localhost:9000/api/upload"
                showUploadList={false}
              >
                <Button type="primary">上传素材</Button>
              </Upload>
            </ImgCrop>
          ) : (
            <Upload
              {...props}
              action="http://localhost:9000/api/upload"
              showUploadList={false}
            >
              <Button type="primary">上传素材</Button>
            </Upload>
          )}
        </Popover>
      </div>
      <div style={{ display: 'flex', justifyContent: 'center', height: '50px' }}>
        <Input placeholder="搜索素材" prefix={<SearchOutlined />} className={style.inp} />
      </div>
      {/* tab切换 */}
      <div style={{ marginLeft: '10px', marginRight: '10px' }}>
        <Tabs defaultActiveKey="0" onChange={onChange} >
          {
            items.map((item: any, index: number) => {
              return <Tabs.TabPane tab={item.label} key={index}>
              </Tabs.TabPane>
            })
          }
        </Tabs>
      </div>
      {/* tab切换内容 */}
      <div className={style.tabmain}>
        <div>
          {/* {
            items.map((item: any, index: any) => {
              return <div key={index}
                style={{ display: key == index ? 'block' : 'none' }}
              >
                {item.contant}
              </div>
            })
          } */}
          {
            key == '0' ?
              <div>
                <div className={style.tabcontainer}>
                  <div className={style.tabtop}>
                    <h3>资源</h3>
                    <p>
                      {fileList.filter((file: any) => file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/svg').length}
                    </p>
                  </div>
                  <SettingOutlined style={{ fontSize: '16px' }} onClick={alldx} />
                </div>
                {
                  bool ? <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div><input type="checkbox" name="" id=""
                      checked={isAllSelected}
                      onChange={handleSelectAll}
                    />已经选择{selectedFiles.length}</div>
                    <div>
                      <DeleteOutlined onClick={delall} />
                      <span style={{ marginLeft: '10px' }} onClick={() => setBool(false)}>取消</span></div>
                  </div> : ''
                }
                <div className={style.imgall}>
                  {fileList.filter((file: any) =>
                    ['image/png', 'image/jpeg', 'image/svg'].includes(file.type))
                    .map((file: any, index: number) => (
                      <div key={index} draggable>
                        <div className={style.picture}>
                          <img src={file.url} alt={file.name} />
                          {bool && <input type="checkbox" className={style.inpbox}
                            checked={selectedFiles.includes(file.name)}
                            onChange={() => dx(file.name)} />}
                        </div>
                      </div>
                    ))}
                </div>
              </div>
              : ''
          }
          {/* 视频 */}
          {
            key == '1' ?
              <div>
                <div className={style.tabcontainer}>
                  <div className={style.tabtop}>
                    <h3>资源</h3>
                    <p>
                      {fileList.filter((item: any) => item.type == 'video/mp4').length}</p>
                  </div>
                  <SettingOutlined style={{ fontSize: '16px' }} onClick={alldx1} />
                </div>
                {
                  bool1 ? <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div>全选视频：<input type="checkbox" name="" id=""
                      checked={isAllSelected1}
                      onChange={handleSelectAll1}
                    />已经选择{selectedvideo.length}</div>
                    <div><DeleteOutlined onClick={delall1} /><span style={{ marginLeft: '10px' }} onClick={() => setBool1(false)}>取消</span></div>
                  </div> : ''
                }
                <div>
                  {rendervideo()}
                </div>
              </div>
              : ''
          }
          {/* 音频 */}
          {
            key == '2' ?
              <div>
                <div className={style.tabcontainer}>
                  <div className={style.tabtop}>
                    <h3>资源</h3>
                    <p>
                      {fileList.filter((item: any) => item.type == 'audio/mpeg').length}</p>
                  </div>
                  <SettingOutlined style={{ fontSize: '16px' }} onClick={alldx2} />
                </div>
                {
                  bool2 ? <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div>全选<input type="checkbox" name="" id=""
                      checked={isAllSelected2}
                      onChange={handleSelectAllaudio}
                    />已经选择{selectedaudio.length}</div>
                    <div><DeleteOutlined onClick={delaudio} /><span style={{ marginLeft: '10px' }} onClick={() => setBool2(false)}>取消</span></div>
                  </div> : ''
                }
                <div>
                  {renderaudio()}
                </div>
              </div>
              : ''
          }
        </div>
      </div>
    </div>
  )
}

export default Index
